<?php
/**
 * --------------------------------------------------------------
 * 配置控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Config as ConfigModel;

class Config extends AdminBase
{
    /**
     * 配置列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = ConfigModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '配置列表'
        ]);
        return $this->fetch();
    }

    /**
     * 设置配置
     */
    public function group($gname = 'base')
    {
        if ($this->request->isPost()) {
            $data  = $this->request->post();
            $items = ConfigModel::where('group', $gname)->where('status', 1)->column('name,type');

            foreach ($items as $name => $type) {
                if (!isset($data[$name])) {
                    switch ($type) {
                        case 'switch':
                            $data[$name] = 0;
                            break;
                        case 'checkbox':
                            $data[$name] = '';
                            break;
                    }
                } else {
                    if (is_array($data[$name])) {
                        $data[$name] = implode(',', $data[$name]);
                    }
                    switch ($type) {
                        case 'switch':
                            $data[$name] = 1;
                            break;
                    }
                }

                ConfigModel::where(['name' => $name])->update(['value' => $data[$name]]);
            }
            config('site_setting', null);
            return $this->success('设置成功', url('group', ['gname' => $gname]));
        } else {
            $map = [
                'status' => 1,
                'group'  => $gname
            ];
            $configs = ConfigModel::queryOneOrList($map, 'id,name,title,options,value,remark,type', 'list', 'sort');

            if ($configs) {
                foreach ($configs as &$value) {
                    if ($value['options'] != '') {
                        $value['options'] = parse_attr($value['options']);
                    }
                    if ($value['type'] == 'daterange') {
                        if (strpos($value['value'], ',') !== false) {
                            list($value_from, $value_to) = explode(',', $value['value']);
                        } else {
                            $value_from = $value['value'];
                            $value_to   = '';
                        }
                        $value['value_from'] = $value_from;
                        $value['value_to']   = $value_to;
                    }
                }
                $this->assign('form_items', $configs);
            }

            $this->assign([
                'gname' => $gname,
                'title' => config('app.site_setting.config_group')[$gname] . '设置'
            ]);
            return $this->fetch();
        }
    }
	
	/**
	 * 新增
	 */
	public function add()
	{
	    if ($this->request->isPost()) {
		    $data        = $this->request->post();
            
            // 验证
            $result   = $this->validate($data, 'Config');
            if (true !== $result) $this->error($result);
			
            if (ConfigModel::create($data)) {
                cache('site_setting', null);
                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
		} else {
            $this->assign([
                'title' => '新增配置'
            ]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
	    if ($this->request->isPost()) {
			$data     = $this->request->post();
            
            // 验证
            $result   = $this->validate($data, 'Config');
            if (true !== $result) $this->error($result);
			
            if (ConfigModel::update($data)) {
                cache('site_setting', null);
                return $this->success('编辑成功', url('index'));
            } else {
                return $this->error('编辑失败');
            }
		} else {
            $info = ConfigModel::get($id);

            $this->assign([
                'info'  => $info,
                'title' => '编辑配置'
            ]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function delete($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
        $map = ['id' => $ids];
		
        $result = ConfigModel::where($map)->delete();
        return $result ? $this->success('删除成功!') : $this->error('删除失败!');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = ConfigModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}